package com.example.clientmanage
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.view.View
import android.view.View.OnClickListener
import android.widget.Toast
import com.example.clientmanage.databinding.ActivityLoginBinding

class LoginActivity : AppCompatActivity(),OnClickListener {
    lateinit var binding: ActivityLoginBinding
    lateinit var handler: Handler
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding= ActivityLoginBinding.inflate(layoutInflater)
        setContentView(binding.root)
        binding.btnLogin.setOnClickListener(this)
        binding.btnRegister.setOnClickListener(this)
        
        // 初始化Handler处理网络请求回调
        handler = object : Handler() {
            override fun handleMessage(msg: Message) {
                if (msg.what == 1) {
                    if (msg.obj.toString() == "T") {
                        Toast.makeText(this@LoginActivity, "登录成功！", Toast.LENGTH_SHORT).show()
                        // 登录成功后跳转到主页面
                        val intent = Intent(this@LoginActivity, MainActivity::class.java)
                        startActivity(intent)
                        finish() // 关闭当前登录活动，防止用户返回到登录界面
                    } else {
                        Toast.makeText(this@LoginActivity, "用户名或密码错误！", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }
    }

    override fun onClick(p0: View?) {
        when(p0?.id)
        {
            R.id.btn_login->{
                val name = binding.etName.text.toString()
                val pwd = binding.etPwd.text.toString()
                
                // 简单的输入验证
                if (name.isEmpty() || pwd.isEmpty()) {
                    Toast.makeText(this, "用户名和密码不能为空！", Toast.LENGTH_SHORT).show()
                    return
                }
                
                // 构建登录请求URL
                var url = "http://192.168.229.24:8080/clientManage/servlet/LoginServlet"
                url = url + "?name=$name&pwd=$pwd"
                
                // 发送网络请求
                val conByGetHttp = ConByGetHttp(url, handler)
                conByGetHttp.start()
            }
            R.id.btn_register->{
                val intent= Intent(this, RegisterActivity::class.java)
                startActivity(intent)
            }
        }
    }
}